import { getCurrentInstance } from "./component";

export function provide(key, value) {
    // 存
    // key value
    const currentInstance: any = getCurrentInstance()
    if (currentInstance) {
        let { provides } = currentInstance;
        const parentProvides = currentInstance.parent.provides;

        // init
        if (provides === parentProvides) {
            provides = currentInstance.provides = Object.create(parentProvides);
        }

        provides[key] = value;
    }
}

export function inject(key, defaultValue) {
    // 取
    const currentInstance: any = getCurrentInstance()
    if (currentInstance) {
        const parentProvides = currentInstance.parent.provides;

        if (key in parentProvides) {
            // 返回父亲provide的值
            return parentProvides[key];
        } else if (defaultValue !== undefined) {
            // 如果默认值是个函数，就执行
            if (typeof defaultValue === 'function') {
                return defaultValue();
            }
            // 如果默认值不是函数，就直接返回
            return defaultValue;
        }
    }
}